#include "WSSprite.h"
#include "WSGlobal.h"

WS_NS_CORE_BEGIN

WSSprite::WSSprite(WSTexture* pTexture, WSRect rect)//texture rect
{
	_pTexture = pTexture;
	SetPinPoint(WSPoint(0.5, 0.5));

	memset(&_Quad, 0, sizeof(_Quad));
	
	WSColor defaultColor(255, 255, 255, 255);
	_Quad.LeftBottom.Color = defaultColor;
	_Quad.LeftTop.Color = defaultColor;
	_Quad.RightBottom.Color = defaultColor;
	_Quad.RightTop.Color = defaultColor;

	SetSize(rect.size);

	float texWidth = _pTexture->GetWidth();
	float texHeight =_pTexture->GetHeight();

	float left, right, top, bottom;
	left = rect.origin.x / texWidth;
	right = (rect.origin.x + rect.size.width) / texWidth;
	top = rect.origin.y / texHeight;
	bottom = (rect.origin.y + rect.size.height) / texHeight;

	_Quad.LeftBottom.Tex = WSTex(left, bottom);
	_Quad.RightBottom.Tex = WSTex(right, bottom);
	_Quad.LeftTop.Tex = WSTex(left, top);
	_Quad.RightTop.Tex = WSTex(right, top);

	_Quad.LeftBottom.Vertex = WSVertex(0, 0);
	_Quad.LeftTop.Vertex = WSVertex(0, _Size.height);
	_Quad.RightBottom.Vertex = WSVertex(_Size.width, 0);
	_Quad.RightTop.Vertex = WSVertex(_Size.width, _Size.height);
}

void WSSprite::Render()
{
	_pTexture->Use();

	int strideSize = sizeof(_Quad.LeftBottom);
	long data = (long)&_Quad;

	glVertexPointer(2, GL_FLOAT, strideSize, (GLvoid*)(data + offsetof(WSVertexColorTex, Vertex)));
	glTexCoordPointer(2, GL_FLOAT, strideSize, (GLvoid*)(data + offsetof(WSVertexColorTex, Tex)));
	glTexCoordPointer(4, GL_UNSIGNED_BYTE, strideSize, (GLvoid*)(data + offsetof(WSVertexColorTex, Color)));

	glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
}

WS_NS_CORE_END